package com.lc.projects.unit.thread.part02.test1;

//使用非依赖属性实现同步
public class Test2 {
	public static void main(String[] args) {
		Cinema cinema = new Cinema();
		TicketOffice1 t1 = new TicketOffice1(cinema);
		TicketOffice2 t2 = new TicketOffice2(cinema);
		
		Thread th1 = new Thread(t1);
		Thread th2 = new Thread(t2);
		
		th1.start();
		th2.start();
		
		try {
			th1.join();
			th2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("C1:"+cinema.getVacanciesCinema1());
		System.out.println("C2:"+cinema.getVacanciesCinema2());
		
	}
}

class Cinema {
	private long vacanciesCinema1;
	private long vacanciesCinema2;
	private Object controleCinema1, controleCinema2;

	public Cinema() {
		controleCinema1 = new Object();
		controleCinema2 = new Object();
		vacanciesCinema1 = 20;
		vacanciesCinema2 = 20;
	}

	public boolean sellTickets1(int number) {
		synchronized (controleCinema1) {
			if (number < vacanciesCinema1) {
				vacanciesCinema1 -= number;
				return true;
			} else {
				return false;
			}
		}
	}

	public boolean sellTickets2(int number) {
		synchronized (controleCinema2) {
			if (number < vacanciesCinema2) {
				vacanciesCinema2 -= number;
				return true;
			} else {
				return false;
			}
		}
	}

	public boolean returnTickets1(int number) {
		synchronized (controleCinema1) {
			vacanciesCinema1 += number;
			return true;
		}
	}

	public boolean returnTickets2(int number) {
		synchronized (controleCinema2) {
			vacanciesCinema2 += number;
			return true;
		}
	}

	public long getVacanciesCinema1() {
		return vacanciesCinema1;
	}

	public long getVacanciesCinema2() {
		return vacanciesCinema2;
	}

}



class TicketOffice1 implements Runnable{
	
	private Cinema cinema;
	
	public  TicketOffice1(Cinema cinema) {
		this.cinema = cinema;
	}
	@Override
	public void run() {
		cinema.sellTickets1(3);
		cinema.sellTickets1(3);
		cinema.sellTickets2(2);
		cinema.returnTickets1(3);
		cinema.sellTickets1(2);
		cinema.sellTickets1(5);
		cinema.sellTickets2(3);
	}
}


class TicketOffice2 implements Runnable{
	
	private Cinema cinema;
	
	public  TicketOffice2(Cinema cinema) {
		this.cinema = cinema;
	}
	@Override
	public void run() {
		cinema.sellTickets1(2);
		cinema.sellTickets1(4);
		cinema.sellTickets2(7);
		cinema.returnTickets2(5);
		cinema.sellTickets2(1);
		cinema.sellTickets2(2);
		cinema.sellTickets2(1);
	}
}






















